package control;
import Manager.Admin;
import Manager.Product;
import User.Cart;
import User.Order;
import javax.swing.plaf.BorderUIResource;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CashierSystem {
    static Scanner scanner = new Scanner(System.in);
    static List<Product> productCatalog = new ArrayList<>();
    static List<Order> orderHistory = new ArrayList<>();
    static Cart userCart = new Cart();
    static final String USER_FILE = "users.txt";
    static final String PRODUCT_FILE = "products.txt";
    static final String CART_FILE_PREFIX = "cart_";
    static final String ORDER_HISTORY_FILE = "order_history.txt";
    public static void main(String[] args) {
        loadProducts();
        loadOrderHistory();
        while (true) {
            showMainMenu();
            int choice = scanner.nextInt();
            scanner.nextLine();  // 吸收换行符
            switch (choice) {
                case 1:
                    handleUserLogin();
                    break;
                case 2:
                    handleUserRegistration();
                    break;
                case 3:
                    handleAdminLogin();
                    break;
                case 4:
                    saveOrderHistory();
                    System.out.println("退出系统");
                    return;
                default:
                    System.out.println("无效选择，请重试");
            }
        }
    }

    private static void saveOrderHistory(){
    }

    private static void showMainMenu() {
        System.out.println("\n======== 网购收银台管理系统 ========");
        System.out.println("1. 用户登录");
        System.out.println("2. 用户注册");
        System.out.println("3. 管理员");
        System.out.println("4. 退出");
        System.out.print("请选择操作: ");
    }
    static void loadProducts() {
        try (BufferedReader reader = new BufferedReader(new FileReader(PRODUCT_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] productDetails = line.split(",");
                if (productDetails.length == 3) {
                    String name = productDetails[0];
                    double price = Double.parseDouble(productDetails[1]);
                    int stock = Integer.parseInt(productDetails[2]);
                    productCatalog.add(new Product(name, price, stock, 0));
                }
            }
        } catch (IOException e) {
            System.out.println("读取商品数据失败: " + e.getMessage());
        }
    }

    static void saveProducts() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(PRODUCT_FILE))) {
            for (Product product : productCatalog) {
                writer.write(product.getName() + "," + product.getPrice() + "," + product.getStock());
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("保存商品数据失败: " + e.getMessage());
        }
    }

    static void handleUserLogin() {
        System.out.println("请输入用户名:");
        String userName = scanner.nextLine();
        System.out.println("请输入密码:");
        String userPassword = scanner.nextLine();

        if (authenticateUser(userName, userPassword)) {
            System.out.println("登录成功，进入用户界面");
            loadCart(userName);
            userMenu(userName);
        } else {
            System.out.println("用户名或密码错误");
        }
    }

    static void handleUserRegistration() {
        System.out.println("请输入用户名(注册):");
        String username = scanner.nextLine();

        if (isUsernameExists(username)) {
            System.out.println("该用户名已存在，请选择另一个用户名");
            return;
        }

        System.out.println("请输入密码(注册):");
        String userpassword = scanner.nextLine();

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(USER_FILE, true))) {
            writer.write(username + "," + userpassword);
            writer.newLine();
            System.out.println("账户注册成功,已为您创建购物车，您现在可以登录");

            // 创建空的购物车文件
            String cartFile = CART_FILE_PREFIX + username + ".txt";
            try (BufferedWriter cartWriter = new BufferedWriter(new FileWriter(cartFile))) {
                // 初始化空购物车，暂时不写入任何内容
                System.out.println("购物车文件创建成功：" + cartFile);
            } catch (IOException e) {
                System.out.println("创建购物车文件失败: " + e.getMessage());
            }
        } catch (IOException e) {
            System.out.println("注册失败: " + e.getMessage());
        }
    }

    static boolean isUsernameExists(String username) {
        try (BufferedReader reader = new BufferedReader(new FileReader(USER_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] userDetails = line.split(",");
                if (userDetails[0].equals(username)) {
                    return true;
                }
            }
        } catch (IOException e) {
            System.out.println("读取用户数据失败: " + e.getMessage());
        }
        return false;
    }

    static boolean authenticateUser(String username, String password) {
        try (BufferedReader reader = new BufferedReader(new FileReader(USER_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] userDetails = line.split(",");
                if (userDetails.length == 2 && userDetails[0].equals(username) && userDetails[1].equals(password)) {
                    return true;
                }
            }
        } catch (IOException e) {
            System.out.println("读取用户数据失败: " + e.getMessage());
        }
        return false;
    }

    static void loadCart(String username) {
        userCart = new Cart();
        String cartFile = CART_FILE_PREFIX + username + ".txt";
        try (BufferedReader reader = new BufferedReader(new FileReader(cartFile))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] productDetails = line.split(",");
                if (productDetails.length == 3) {
                    String name = productDetails[0];
                    double price = Double.parseDouble(productDetails[1]);
                    int quantity = Integer.parseInt(productDetails[2]);
                    userCart.addProduct(new Product(name, price, quantity, 0));
                }
            }
        } catch (IOException e) {
            //System.out.println("读取购物车数据失败: " + e.getMessage());
        }
    }

    static void saveCart(String username) {
        String cartFile = CART_FILE_PREFIX + username + ".txt";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(cartFile))) {
            for (Product product : userCart.products) {
                writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity());
                writer.newLine();
            }
        } catch (IOException e) {
            System.out.println("保存购物车数据失败: " + e.getMessage());
        }
    }

    static void handleAdminLogin() {
        System.out.println("请输入管理员密码:");
        int n = 3;
        while (true) {
            String pas = scanner.nextLine();
            if (pas.equals("654321")) {
                System.out.println("密码正确,已进入管理员界面");
                adminMenu();
                break;
            } else {
                n--;
                System.out.println("密码错误，还剩" + n + "次机会");
                if (n == 0) {
                    break;
                }
            }
        }
    }

    static void userMenu(String username) {
        while (true) {
            showUserMenu();
            int choice = scanner.nextInt();
            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    addToCart();
                    saveCart(username);
                    break;
                case 3:
                    viewCart();
                    break;
                case 4:
                    removeFromCart();
                    saveCart(username);
                    break;
                case 5:
                    placeOrder();
                    saveCart(username);
                    break;
                case 6:
                    payOrder();
                    break;
                case 7:
                    refundOrder();
                    break;
                case 8:
                    saveCart(username);
                    return;
                default:
                    System.out.println("无效选择，请重试");
            }
        }
    }

    static void showUserMenu() {
        System.out.println("\n======== 用户菜单 ========");
        System.out.println("1. 浏览商品");
        System.out.println("2. 添加商品至购物车");
        System.out.println("3. 查看购物车");
        System.out.println("4. 删除购物车里的商品");
        System.out.println("5. 下单");
        System.out.println("6. 支付");
        System.out.println("7. 退款");
        System.out.println("8. 返回主菜单");
        System.out.print("请选择操作: ");
    }

    static void browseProducts() {
        System.out.println("\n商品目录:");
        for (int i = 0; i < productCatalog.size(); i++) {
            System.out.println((i + 1) + ". " + productCatalog.get(i));
        }
    }

    static void addToCart() {
        browseProducts();
        System.out.print("请选择要添加至购物车的商品编号: ");
        int productIndex = scanner.nextInt() - 1;
        if (productIndex >= 0 && productIndex < productCatalog.size()) {
            userCart.addProduct(productCatalog.get(productIndex));
        } else {
            System.out.println("无效的商品编号");
        }
    }

    static void viewCart() {
        userCart.showCart();
    }

    static void removeFromCart() {
        userCart.showCart();
        System.out.print("请选择要移除的商品编号: ");
        int productIndex = scanner.nextInt() - 1;
        if (productIndex >= 0 && productIndex < productCatalog.size()) {
            userCart.removeProduct(productCatalog.get(productIndex));
        } else {
            System.out.println("无效的商品编号");
        }
    }

    static void placeOrder() {
        if (userCart.products.isEmpty()) {
            System.out.println("购物车为空，无法下单");
        } else {
            Order order = new Order();
            order.products.addAll(userCart.products);
            orderHistory.add(order);
            saveOrderToFile(order);
            userCart.products.clear();
            System.out.println("下单成功，请前往支付");
        }
    }

    static void payOrder() {
        if (orderHistory.isEmpty()) {
            System.out.println("没有待支付的订单");
        } else {
            Order latestOrder = orderHistory.get(orderHistory.size() - 1);
            latestOrder.pay();
        }
    }

    static void refundOrder() {
        if (orderHistory.isEmpty()) {
            System.out.println("没有订单可以退款");
        } else {
            Order latestOrder = orderHistory.get(orderHistory.size() - 1);
            latestOrder.refund();
        }
    }

    static void adminMenu() {
        while (true) {
            showAdminMenu();
            int choice = scanner.nextInt();
            scanner.nextLine();  // 吸收换行符
            switch (choice) {
                case 1:
                    Admin.addProduct(productCatalog);
                    saveProducts();
                    break;
                case 2:
                    Admin.deleteProduct(productCatalog);
                    saveProducts();
                    break;
                case 3:
                    Admin.updateProduct(productCatalog);
                    saveProducts();
                    break;
                case 4:
                    Admin.queryProduct(productCatalog);
                    break;
                case 5:
                    Admin.salesStatistics(orderHistory);
                    break;
                case 6:
                    Admin.stockStatistics(productCatalog);
                    break;
                case 7:
                    viewAllOrderHistory();
                    break;
                case 8:
                    return;
                default:
                    System.out.println("无效选择，请重试");
            }
        }
    }
    static void showAdminMenu() {
        System.out.println("\n======== 管理员菜单 ========");
        System.out.println("1. 增加商品");
        System.out.println("2. 删除商品");
        System.out.println("3. 修改商品");
        System.out.println("4. 查询商品");
        System.out.println("5. 销售统计");
        System.out.println("6. 库存统计");
        System.out.println("7. 查看所有历史订单");
        System.out.println("8. 返回主菜单");
        System.out.print("请选择操作: ");
    }


    static void saveOrderToFile(Order order) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(ORDER_HISTORY_FILE, true))) {
            writer.write("订单号：" + orderHistory.size());
            writer.newLine();
            for (Product product : order.products) {
                writer.write(product.getName() + "," + product.getPrice() + "," + product.getQuantity());
                writer.newLine();
            }
            writer.write("-----------");
            writer.newLine();
        } catch (IOException e) {
            System.out.println("保存订单数据失败: " + e.getMessage());
        }
    }

    static void viewAllOrderHistory() {
        System.out.println("\n所有历史订单：");
        try (BufferedReader reader = new BufferedReader(new FileReader(ORDER_HISTORY_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("读取历史订单数据失败: " + e.getMessage());
        }
    }
    static void loadOrderHistory() {
        try (BufferedReader reader = new BufferedReader(new FileReader(ORDER_HISTORY_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("订单号")) {
                    Order order = new Order();
                    while (!(line = reader.readLine()).equals("-----------")) {
                        String[] productDetails = line.split(",");
                        if (productDetails.length == 3) {
                            String name = productDetails[0];
                            double price = Double.parseDouble(productDetails[1]);
                            int quantity = Integer.parseInt(productDetails[2]);
                            order.products.add(new Product(name, price, quantity, 0));
                        }
                    }
                    orderHistory.add(order);
                }
            }
        } catch (IOException e) {
            System.out.println("读取历史订单数据失败: " + e.getMessage());
        }
    }
}
